
/**
*This software is under LGPL license,
*see http://www.gnu.org/licenses/lgpl-3.0.txt (C) 2007 Free Software Foundation, Inc. <http://fsf.org/>)
*Console.h First issued by chuanshenglu@gmail.com 2008.10
*/
#include "TRSession.h"

namespace TR{
	//Cons and des
	TRSession::TRSession()
	{
	}
	TRSession::TRSession(Console &console)
		:mConsole(&console),mMode(TRSession::COMMAND)
	{
		mConsole->AddKeyboardEventListener(this);
		mConsole->AddFocusEventListener(this);
	}
	TRSession::TRSession(TR::TRSession &session){
	}
	TRSession::~TRSession(){
	}

	//Process event
	void TRSession::OnKeyDown(KeyboardEvent& e){
		switch(e.wVirtualKeyCode){
			case VK_ESCAPE:
				mMode=(mMode==COMMAND)?EDIT:COMMAND;
				if(mMode==COMMAND){
					mCommandBuf.clear();
					mConsole->ShowCursor(TRUE);
					mConsole->MoveCursor(Coord(0,mConsole->GetHeight()-1));
					//Clear the command erea;
					for(uint32 i=0;i<mConsole->GetWidth()-1;i++)
						mConsole->WriteChar(Coord(i,mConsole->GetHeight()-1),' ');
					mConsole->MoveCursor(Coord(0,mConsole->GetHeight()-1));
				}else{
					//mConsole->MoveCursor(Coord(0,0));
					mConsole->ShowCursor(FALSE);
					for(uint32 i=0;i<mConsole->GetWidth()-1;i++)
						mConsole->WriteChar(Coord(i,mConsole->GetHeight()-1),' ');
				}
				break;
			case VK_F1://Press F1 to quit,temp config
				exit(0);
				break;
			default:
				if(mMode==COMMAND){
					if(e.wVirtualKeyCode==VK_RETURN)
						ExecuteCommand();
					else{
						//skip control chars;
						if(e.uChar.AsciiChar>=33 && e.uChar.AsciiChar<=126)
							mCommandBuf+=e.uChar.UnicodeChar;
						wcout<<e.uChar.UnicodeChar;
					}
				}
		}
	}

	void TRSession::ExecuteCommand(){
		mConsole->MoveCursor(Coord(0,0));
		//wcout<<TEXT("Command executed!")<<endl;
		//Execute command;
		ParseAndExec();
		mCommandBuf.clear();
		mMode=EDIT;
	}
	void TRSession::ParseAndExec(){
		/**
		*'o filename' will open a file and display it in the console;
		*/
		if(mCommandBuf.at(0)==TCHAR('o')){
			String filename=mCommandBuf.substr(1,mCommandBuf.length()-1);
			ifstream file;
			file.open(filename.c_str(),ios::binary);
			if(!file){
				wcout<<TEXT("Fail to open file")<<filename<<endl;
			}else{
				static char ch=0;
				char tch=0;
				while(!file.eof()){
					file>>tch;
					//if(tch!=0xFF)
					cout<<tch;
					if(ch==0xD && tch==0xA)
						mConsole->MoveCursor(Coord(mConsole->GetCursorPos().X,mConsole->GetCursorPos().Y+1));
					if(tch==0x9)
						cout<<'\t';
					//if(tch==TCHAR('\n'))// || tch==TCHAR('\0'))
					//	wcout<<endl;
					ch=tch;
				}
				file.close();
			}
		}

		/**
		*"quit"will quit TR
		*/
		if(mCommandBuf.substr(0,4).compare(TEXT("quit"))==0){
			exit(0);
		}
	}
}